#include "stm32f10x.h"                  // Device header
#include "delay.h"


void Myi2c_write_sclk(unsigned char Bit)
{
	GPIO_WriteBit(GPIOB,GPIO_Pin_0,(BitAction)Bit);
	Delay_us(10);
}

unsigned char Myi2c_read_sclk(void)
{
	unsigned char sclk;
	sclk=GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_0);
	return sclk;
}

void Myi2c_write_sda(unsigned char Bit)
{
	GPIO_WriteBit(GPIOB,GPIO_Pin_1,(BitAction)Bit);
	Delay_us(10);
}

unsigned char Myi2c_read_sda(void)
{
	unsigned char sda;
	sda=GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_1);
	return sda;
}

void Myi2c_init(void)
{
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);
	GPIO_InitTypeDef Myi2c_gpio;
	Myi2c_gpio.GPIO_Mode=GPIO_Mode_Out_OD;
	Myi2c_gpio.GPIO_Pin=GPIO_Pin_0 | GPIO_Pin_1;
	Myi2c_gpio.GPIO_Speed=GPIO_Speed_50MHz;
	GPIO_Init(GPIOB,&Myi2c_gpio);
	
	GPIO_SetBits(GPIOB,GPIO_Pin_0 | GPIO_Pin_1);
}


void Myi2c_start(void)
{
	Myi2c_write_sda(1);
	Myi2c_write_sclk(1);
	Myi2c_write_sda(0);
	Myi2c_write_sclk(0);	
}

void Myi2c_stop(void)
{
	Myi2c_write_sclk(0);
	Myi2c_write_sda(0);
	Myi2c_write_sclk(1);
	Myi2c_write_sda(1);
}

void Myi2c_send_byte(unsigned char byte)
{
	Myi2c_write_sclk(0);
	for(int i=0;i<8;i++)
	{
		Myi2c_write_sda(byte & (0x80>>i));
		Myi2c_write_sclk(1);
		Myi2c_write_sclk(0);
	}
}

unsigned char Myi2c_receive_byte(void)
{
	unsigned char data=0x00;
	Myi2c_write_sda(1);
	for(int i=0;i<8;i++)
	{
		Myi2c_write_sclk(1);	
		if(Myi2c_read_sda()==1)
		{
			data |= (0x80>>i);
		}
		Myi2c_write_sclk(0);
	}
	return data;
}

void Myi2c_send_ack(unsigned char ack)
{
		Myi2c_write_sda(ack);
		Myi2c_write_sclk(1);
		Myi2c_write_sclk(0);		
}

unsigned char Myi2c_receive_ack(void)
{
	unsigned char ack;
	Myi2c_write_sda(1);	
	Myi2c_write_sclk(1);
	ack=Myi2c_read_sda();
	Myi2c_write_sclk(0);		
	return ack;
}


